package org.simple.webserver.server;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.AbstractServerHttpRequest;
import org.springframework.http.server.reactive.SslInfo;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;

import java.net.InetSocketAddress;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;

/**
 * @author HaiLang
 * @date 2021/8/22 10:10 下午
 */
public class MyServerHttpRequest extends AbstractServerHttpRequest {

    private final MultiValueMap<String, HttpCookie> cookies;

    private final String methodName;

    private final List<String> body;

    private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(false);

    public MyServerHttpRequest(URI uri, String contextPath, HttpHeaders headers,
                               @Nullable MultiValueMap<String, HttpCookie> cookies,
                               String methodName, @Nullable List<String> body) {
        super(uri, contextPath, headers);
        this.cookies = cookies;
        this.methodName = methodName;
        this.body = body;
    }

    @Override
    protected final MultiValueMap<String, HttpCookie> initCookies() {
        return this.cookies;
    }

    @Override
    protected SslInfo initSslInfo() {
        return null;
    }

    @Override
    public final <T> T getNativeRequest() {
        return (T) this;
    }

    @Override
    public final String getMethodValue() {
        return this.methodName;
    }

    @Override
    public final Flux<DataBuffer> getBody() {
        return CollectionUtils.isEmpty(body) ?
                Flux.empty() :
                Flux.fromStream(() -> {
                    List<DataBuffer> list = new LinkedList<>();
                    for (String line : body) {
                        list.add(bufferFactory.wrap(line.getBytes()));
                    }
                    return list.stream();
                });
    }

    @Override
    public final InetSocketAddress getLocalAddress() {
        //在nginx.conf的配置中
        return new InetSocketAddress("localhost", 8888);
    }

    @Override
    public final InetSocketAddress getRemoteAddress() {
        throw new UnsupportedOperationException();
    }

}
